import axios from "axios";
import store from "../store";
import router from "../router";
import { CLEAR_TOKEN } from "../store/mutation-types";
import { NETWORK_ERR, INVALID_PATH, SERVER_ERROR, LOGIN_EXPIRE, NO_AUTHORITY } from "@/config/util/constant";
import { Message } from "element-ui";

axios.defaults.timeout = 30000;

const logout = () => {
  store.state.token && console.warn(`token[${store.state.token}]失效`);
  Message.error(LOGIN_EXPIRE);
  // 清除token信息并跳转到登录页面
  store.commit(CLEAR_TOKEN);
  router.replace({
    name: "login",
    query: {
      redirect: router.currentRoute.fullPath
    }
  });
};

// http request 拦截器
axios.interceptors.request.use(
  config => {
    if (store.state.token) {
      config.headers.token = store.state.token;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });

// http response 拦截器
axios.interceptors.response.use(
  response => {
    const { code = 0 } = response.data;
    switch (code) {
      case 401:
        logout();
        break;
    }
    return response.data;
  },
  error => {
    const { response = {} } = error || {};
    let msg = NETWORK_ERR;
    switch (response.status) {
      case 401:
        logout();
        break;
      case 403:
        Message.error(NO_AUTHORITY);
        msg = NO_AUTHORITY;
        break;
      case 404:
        Message.error(INVALID_PATH);
        msg = INVALID_PATH;
        break;
    }
    if (Math.floor(response.status / 100) === 5) {
      msg = SERVER_ERROR;
    }
    msg && Message.error(msg);
    // 这里使用 resolve 就不再在每个请求中去处理 catch 了
    return Promise.resolve({ code: -1, msg });
  });

export default axios;
